@Scheduled(fixedDelay = 100L) public void product() { User user = new User(); user.setId(24545); user.serName("lvk"); user.setAdress("GDGZTH"); this.rabbitTemplate.convertAndSend("queueName", user); } }
消费者
1 2 3 4 5 6 7 8 9 10 11
@Service @RabbitListener(queues = "queueName") public class Consumer { protected Logger logger = Logger.getLogger(Consumer.class); @RabbitHandler public void process(@Payload User user) { UserResponse response = new UserResponse(); logger.info(user.getId() + "->" + response.getRetCode()); } }
看控制台日志输出:
1 2 3
org.springframework.amqp.AmqpException: No method found for class
死循环似的输出......
解决方案如下
在初始化的时候先构建如下两个bean:
RabbitTemplate
1 2 3 4 5 6 7
@Bean public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate template = new RabbitTemplate(connectionFactory); template.setMessageConverter(new Jackson2JsonMessageConverter()); return template; }
SimpleRabbitListenerContainerFactory (消息监听器工厂)
1 2 3 4 5 6 7 8
@Bean public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(connectionFactory); factory.setMessageConverter(new Jackson2JsonMessageConverter()); return factory; }
然后将以上消费者的代码修改为如下:
1 2 3 4 5 6 7 8 9 10 11 12
@Service public class Consumer { protected Logger logger = Logger.getLogger(Consumer.class);
@RabbitListener(queues = "queueName", containerFactory="rabbitListenerContainerFactory") public void process(@Payload User user) { UserResponse response = new UserResponse(); logger.info(request.getId() + "->" + response.getRetCode()); } }